package com.cloudfun.msglisten.util.haier;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.net.URL;
import java.security.MessageDigest;

@Slf4j
public class UhomeUtils {

    private static String APP_ID = "SV-QLKJ545-0000";

    private static String APP_KEY = "ca11183ad4b15dbe686892c09bf3cd3c";

    private static String APP_KEY_PROD = "ad95ee74c2d94644a075eb81d72391a8";


    @SneakyThrows
    public static String getSign(String appId, String appKey, String timestamp, String body, String url) {
        URL urlObj = new URL(url);
        url = urlObj.getPath();
        appKey = appKey.trim();
        appKey = appKey.replaceAll("\"", "");
        if (body != null) {
            body = body.trim();
        }
        if (!body.equals("")) {
            body = body.replaceAll(" ", "");
            body = body.replaceAll("\t", "");
            body = body.replaceAll("\r", "");
            body = body.replaceAll("\n", "");
        }
        log.info("body:" + body);
        StringBuffer sb = new StringBuffer();
        sb.append(url).append(body).append(appId).append(appKey).append(timestamp);

        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            bytes = md.digest(sb.toString().getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }

        return binaryToHexString(bytes);
    }

    public static String getSign(String systemId, String systemKey, String timestamp) {
        systemKey = systemKey.trim();
        systemKey = systemKey.replaceAll("\"", "");

        StringBuffer sb = new StringBuffer();
        sb.append(systemId).append(systemKey).append(timestamp);
        MessageDigest md = null;
        byte[] bytes = null;
        try {
            md = MessageDigest.getInstance("SHA-256");
            bytes = md.digest(sb.toString().getBytes("utf-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return binaryToHexString(bytes);
    }

    public static String binaryToHexString(byte[] bytes) {
        StringBuilder hex = new StringBuilder();
        String hexStr = "0123456789abcdef";
        for (int i = 0; i < bytes.length; i++) {
            hex.append(String.valueOf(hexStr.charAt((bytes[i] & 0xF0) >> 4)));
            hex.append(String.valueOf(hexStr.charAt(bytes[i] & 0x0F)));
        }
        return hex.toString();
    }

}
